<?php

namespace app\admin\controller;
use think\Session;
use think\Loader;
use think\Config;
use app\common\model\AuthGroup;
use app\common\model\User;
class PersonalController extends BaseController{
  public function _initialize(){
    parent::_initialize();
    $this->Model = new User();
  }

  // 修改个人信息
  public function profile(){
    $user = login_manager();
    if($this->request->isPost()){
      $data = [];
      $param_name = ["email", "avatar", "mobile", "gender", "birthday"];
      $post = $this->request->post();
      foreach ($param_name as $key) {
        if(isset($post[$key])){
          $val = $post[$key];
        }else{
          $val = "";
        }

        switch ($key) {
        case "birthday":
          if(empty($val)){
            $val = NULL;
          }
          break;
        default:
          $val = trim($val);  
        }
        $data[$key] = $val;
      }

      $res = $this->Model->updateBaseInfo("manager", $data, $user["id"]);
      if($res["status"]){
        $param = ["id" => $user["id"], "user_type" => "manager"];
        $user = $this->Model->reloadUserInfo($param);
        Session::set("manager", $user);
        Session::flash("notice", "更新个人信息成功");
        $this->success($res["msg"], 'profile');
      }else{
        $this->error($res["msg"]);
      }
    }else{
      $GroupModel = new AuthGroup();
      $group = $GroupModel->userGroup($user["id"]);
      if($group){
        $group_title = $group["title"];
      }else{
        $group_title = "";
      }
      $notice = Session::pull('notice');
      $this->assign("notice", $notice);
      $this->assign("group_title", $group_title);
      $this->assign("user", $user);
      return $this->fetch();
    }
  }

  // 修改登录密码
  public function change_password(){
    $user = login_manager();
    if($this->request->isPost()){
      $data = [];
      $param_name = ["old_password", "password", "confirm_password"];
      $post = $this->request->post();
      foreach ($param_name as $key) {
        if(isset($post[$key])){
          $val = $post[$key];
          $val = trim($val);
        }else{
          $val = "";
        }

        $data[$key] = $val;
      }

      $res = $this->Model->changePassword($user["id"], $data);
      if($res["status"]){
        Session::flash("notice", "更新密码成功");
        $this->success($res["msg"], "change_password");
      }else{
        $this->error($res["msg"]);
      }
    }else{
      $notice = Session::pull('notice');
      $this->assign("notice", $notice);
      return $this->fetch();
    }
  }

  //验证用户登录密码
  public function ajax_valid_password(){
    $password = $this->request->post("old_password");
    $user_id = login_manager_id();
    $valid_res = $this->Model->validPassword($user_id, $password);
    echo($valid_res);
  }
}